
package com.be.beadmin.quality.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.basicData.service.RoleService;
import com.be.beadmin.basicData.service.UserService;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.product.entity.ProductManufactInfor;
import com.be.beadmin.product.entity.WorkOrderInfor;
import com.be.beadmin.product.repository.WorkOrderInforRepository;
import com.be.beadmin.product.service.ProductManufactInforService;
import com.be.beadmin.product.service.WorkOrderInforService;
import com.be.beadmin.project.entity.BatchPlan;
import com.be.beadmin.project.entity.BatchProduct;
import com.be.beadmin.project.entity.Info;
import com.be.beadmin.project.service.BatchPlanService;
import com.be.beadmin.project.service.BatchProductService;
import com.be.beadmin.project.service.InfoService;
import com.be.beadmin.quality.dto.input.InspectionMasterValueDto;
import com.be.beadmin.quality.dto.output.InspectionMasterValueEx;
import com.be.beadmin.quality.entity.*;
import com.be.beadmin.quality.mapper.InspectionMasterValueMapper;
import com.be.beadmin.quality.mapper.InspectionMasterValueMapperEx;
import com.be.beadmin.quality.repository.InspectionMasterValueRepository;
import com.be.beadmin.quality.repository.InspectionTemplateMasterItemRepository;
import com.be.beadmin.quality.service.InspectionMasterValueService;
import com.be.beadmin.service.util.DateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description
* @author zjm
* @date 2023-05-28
**/
@Service
@RequiredArgsConstructor
public class InspectionMasterValueServiceImpl implements InspectionMasterValueService {

    @Autowired
    private  InspectionMasterValueRepository inspectionMasterValueRepository;
    @Autowired
    private  UserService userService;
    @Autowired
    private WorkOrderInforRepository workOrderInforRepository;
    @Autowired
    private RoleService roleService;
    @Autowired
    private InfoService infoService;
    @Autowired
    private ProductManufactInforService productManufactInforService;
    @Autowired
    private BatchProductService batchProductService;
    @Autowired
    private BatchPlanService batchPlanService;
    @Autowired
    private  InspectionMasterValueMapper inspectionMasterValueMapper;
    @Autowired
    private  InspectionMasterValueMapperEx inspectionMasterValueExMapper;

    @Autowired
    private InspectionTemplateMasterItemRepository inspectionTemplateMasterItemRepository;

    @Override
    public Page<InspectionMasterValueEx> getInspectionMasterValueByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<InspectionMasterValue> page = inspectionMasterValueRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectionMasterValue_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectionMasterValue_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<InspectionMasterValueEx> page1 = page.map(inspectionMasterValueExMapper::toEntity);
            return page1;

    }

    @Override
    public void addInspectionMasterValue(InspectionMasterValueDto inspectionMasterValueDto) {
            InspectionMasterValue result = inspectionMasterValueRepository.findInspectionMasterValueByIdAndDelete(inspectionMasterValueDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("InspectionMasterValue不存在,请重新查询");
            }
            InspectionMasterValue inspectionMasterValue = inspectionMasterValueMapper.toEntity(inspectionMasterValueDto);
            inspectionMasterValueRepository.save(inspectionMasterValue);
    }

    @Override
    public void updateInspectionMasterValue(InspectionMasterValueDto inspectionMasterValueDto) {
            InspectionMasterValue inspectionMasterValue = inspectionMasterValueRepository.findInspectionMasterValueById(inspectionMasterValueDto.getId());
            inspectionMasterValue = inspectionMasterValueMapper.toEntity(inspectionMasterValueDto);
            inspectionMasterValueRepository.save(inspectionMasterValue);
    }


    @Override
    public void delInspectionMasterValue(String id) {
        InspectionMasterValue inspectionMasterValue = inspectionMasterValueRepository.findInspectionMasterValueById(id);
        inspectionMasterValue.setDelete(1);
        inspectionMasterValueRepository.save(inspectionMasterValue);
    }

    @Override
    public void delInspectionMasterValues (List<String> ids) { }

    /**
     * 生成自定义项目值
     *
     * @param save
     * @param template
     */
    @Override
    public void generateInspectionMasterValue(InspectionTask save, InspectionTemplate template) {

        for (InspectionTemplateMasterItem inspectionTemplateMasterItem : inspectionTemplateMasterItemRepository.findInspectionTemplateMasterItemByInspectionTemplateIdAndDelete(template.getId(), 0)) {
            InspectionMasterValue inspectionMasterValue = new InspectionMasterValue();
            inspectionMasterValue.setInspectionTaskId(save.getId());
            inspectionMasterValue.setTemplateCustomItemId(inspectionTemplateMasterItem.getId());
            setMasterValue(save,inspectionTemplateMasterItem,inspectionMasterValue);
//            inspectionMasterValue.set(template.getId());
            inspectionMasterValueRepository.save(inspectionMasterValue);
        }
    }

    private void setMasterValue(InspectionTask save,InspectionTemplateMasterItem inspectionTemplateMasterItem, InspectionMasterValue inspectionMasterValue) {
//        if (save.getType().equals("柜体入厂检验"));{
//
//        }
        Info info = infoService.getInfoIdById(save.getInfoId());
//        ProductManufactInfor productManufactById = productManufactInforService.getProductManufactById(save.getProcessId());
        BatchProduct batchProductById = null;
        if (save.getWo() != null) {
            WorkOrderInfor workOrderInfor = workOrderInforRepository.findWorkOrderInforByWoAndDelete(save.getWo(), 0);
            if (workOrderInfor!= null) {
                batchProductById = batchProductService.getBatchProductById(workOrderInfor.getBatchProductId());
            }
        }

        BatchPlan batchPlanById = batchPlanService.getBatchPlanById(save.getBatchPlanId());
        String name = inspectionTemplateMasterItem.getName();
        if (name == null) {
            return;
        }
        switch (name.trim()) {
            case "项目名称":
                if (info!=null) inspectionMasterValue.setTemplateCustomItemValue(info.getProjectName());
                break;
            case "项目编号":
                if (info!=null) inspectionMasterValue.setTemplateCustomItemValue(info.getProjectCode());
                break;
            case "批次":
                if (batchProductById!=null) inspectionMasterValue.setTemplateCustomItemValue(batchProductById.getBatchPlanCode());
                break;
            case "柜体数量":
                if (batchPlanById!=null) inspectionMasterValue.setTemplateCustomItemValue(String.valueOf(batchPlanService.countProductByBatchPlan(batchPlanById.getId())) );
                break;
            case "箱子数量":
                if (batchPlanById!=null) inspectionMasterValue.setTemplateCustomItemValue(String.valueOf(batchPlanService.countProductByBatchPlanAndType(batchPlanById.getId(),"箱体")) );
                break;
            case "合同号":
                if (info!=null) inspectionMasterValue.setTemplateCustomItemValue(info.getContractCode());
                break;
            case "电柜序列号":
            case "电柜编号":
            case "电柜系列号":
            case "产品系列号":
                if (batchProductById!=null) inspectionMasterValue.setTemplateCustomItemValue(batchProductById.getProductCode());
                break;
            case "生产班组":
            case "班组":
                inspectionMasterValue.setTemplateCustomItemValue(save.getType()+"组");
                break;
            case "操作者":
                inspectionMasterValue.setTemplateCustomItemValue("-");
                break;
            case "日期":
                inspectionMasterValue.setTemplateCustomItemValue(DateUtil.transDateFormatToString(new Date()));
                break;


        }

    }
}